<template>
  <common-page :common-ins="commonIns" :action-bar-data="actionBarData" :columns="columns">
    <dialog-form ref="dialog" @confirm="dialogFn.confirm"></dialog-form>

    <!-- 字典值列表 -->
    <dialog-value-list ref="valueList" @table-fn="dialogFn.dialogListAction"></dialog-value-list>

    <!-- 字典之表单 -->
    <dialog-value-form ref="valueForm" @confirm="dialogFn.valueConfirm"></dialog-value-form>
  </common-page>
</template>

<script setup lang="ts">
import { TableRowData } from 'tdesign-vue-next';
import { ref } from 'vue';

import $api from '@/api';
import { $confirm, dialog, useCommon } from '@/hooks/common';
import { t } from '@/locales';
import CommonPage from '@/pages/common/page/index.vue';
import { mitter } from '@/utils/mitt';

import DialogForm from './components/DialogForm.vue';
import DialogValueForm from './components/DialogValueForm.vue';
import DialogValueList from './components/DialogValueList.vue';
import { ACTION_BAR_DATA, COLUMNS } from './constants';

const API = $api.system.dict;

const actionBarData = ref([...ACTION_BAR_DATA]);
const columns = ref(...[COLUMNS]);
const commonIns = useCommon({ API });

const curDict = ref(null);
const valueList = ref(null);
const valueForm = ref(null);

const dialogFn: Recordable = {
  ...commonIns.dialogFn,
  updateList: async () => {
    const list = await API.valueList({ id: curDict.value.id });
    valueList.value.update(list);
  },
  dialogListShow(data: any) {
    valueList.value.dialogShow('edit', data);
  },
  async dialogListAction(type: string, row: TableRowData) {
    const fnMap: Recordable = {
      add() {
        valueForm.value.dialogShow('add');
      },
      async listorder() {
        await API.valueListorder({ id: row.id, listorder: row.listorder });
        dialogFn.updateList();
      },
      async display() {
        await API.valueDisplay(row.id, row.display);
      },
      async edit() {
        const data = await API.valueDetail(row.id);
        valueForm.value.dialogShow('edit', data);
      },
      async delete() {
        $confirm({ theme: 'danger', body: t('common.deleteConfirm') }, async () => {
          await API.valueDel(row.id);
          dialogFn.updateList();
        });
      },
    };

    fnMap[type]();
  },
  async valueConfirm(type: 'add' | 'edit', data: any) {
    const method = type === 'add' ? 'valueAdd' : 'valueUpdate';
    try {
      await API[method]({ ...data, dict: curDict.value.id });
      valueForm.value.dialogHide();
      dialogFn.updateList();
    } catch (error) {
      valueForm.value.loadingClear();
    }
  },
};

const tableFn: Recordable = {
  ...commonIns.tableFn,
  async editContent(row: TableRowData) {
    curDict.value = row;

    const list = await API.valueList({ id: row.id });
    dialogFn.dialogListShow({ title: row.name, list });
  },
};

mitter.on('content', (row: TableRowData) => {
  tableFn.editContent(row);
});
</script>
